// 通过session判断是否登录，登录有key = users 这个对象值
export function isLogin(){
  let user = sessionStorage.getItem('user')
  const pathname = window.location.pathname;
  sessionStorage.setItem('url', pathname);
  if(!user) return false;
  let temp = JSON.parse(user);
  return isExistUser(temp);
}

export function getUser(){
  let user = sessionStorage.getItem('user')
  if(!user) return null;
  let temp = JSON.parse(user);
  if (isExistUser(temp)) return temp;
}

export function getUserId(){
  let user = sessionStorage.getItem('user')
  if(!user) return null;
  let temp = JSON.parse(user);
  return temp.id
}

export function getUserName(){
  let user = sessionStorage.getItem('user')
  if(!user) return null;
  let temp = JSON.parse(user);
  return temp.username
}

export function getByParam(param){
  let user = sessionStorage.getItem('user')
  if(!user) return null;
  let temp = JSON.parse(user);
  return temp[param]
}


export function isExistUser(temp){
  let users = findUsers();
  let user = users.find(u=>u.username == temp.username && u.password == temp.password)
  if (user){
    return true;
  }else{
    return false;
  }
}

export function findUserByUsername(username){
  let users = JSON.parse(localStorage.getItem('users') || "[]");
  return users.find(item=>item.username === username)
}

export function findUsers(){
  return JSON.parse(localStorage.getItem('users') || "[]");
}

export function addUser(user){
  if(!isExistUser(user)){
    let users = JSON.parse(localStorage.getItem('users') || "[]");
    localStorage.setItem('users',JSON.stringify([...users, user]));
  }
}
